<template>
  <div id="app">
    <h1>在线生成视频</h1>

    <div>
      <label for="width">宽度:</label>
      <input id="width" v-model.number="width" type="number" min="1" />

      <label for="height">高度:</label>
      <input id="height" v-model.number="height" type="number" min="1" />

      <label for="fps">帧率:</label>
      <input id="fps" v-model.number="fps" type="number" min="1" />

      <label for="duration">时长 (秒):</label>
      <input id="duration" v-model.number="duration" type="number" min="1" />

      <button @click="generateVideo" :disabled="loading">
        {{ loading ? '生成中...' : '生成视频' }}
      </button>
    </div>

    <div v-if="videoURL">
      <h2>预览视频:</h2>
      <video
        :src="videoURL"
        controls
        style="max-width: 100%; height: auto"
      ></video>
      <a ref="downloadLink" :href="videoURL" :download="filename">下载视频</a>
      <p>文件大小: {{ fileSize }}</p>
    </div>
  </div>
</template>

<script>
import Whammy from 'whammy'

export default {
  data() {
    return {
      width: 1920,
      height: 1080,
      fps: 30,
      duration: 60,
      videoURL: null,
      loading: false,
      filename: 'generated-video.webm',
      fileSize: null
    }
  },
  methods: {
    async generateVideo() {
      this.loading = true
      this.videoURL = null
      this.fileSize = null

      const frameCount = this.fps * this.duration
      const canvas = document.createElement('canvas')
      canvas.width = this.width
      canvas.height = this.height
      const ctx = canvas.getContext('2d')
      const video = new Whammy.Video(this.fps)

      for (let i = 0; i < frameCount; i++) {
        // 清空画布
        ctx.clearRect(0, 0, this.width, this.height)

        // 在画布上绘制内容，这里以随机颜色为例
        ctx.fillStyle = `hsl(${Math.random() * 360}, 100%, 50%)`
        ctx.fillRect(0, 0, this.width, this.height)

        // 添加帧到视频
        video.add(canvas)
      }

      // 创建视频 Blob 对象
      const blob = video.compile()
      const url = URL.createObjectURL(blob)
      this.videoURL = url
      this.fileSize = `${(blob.size / (1024 * 1024)).toFixed(2)} MB` // 文件大小，单位为 MB
      this.filename = `generated-video-${this.width}x${this.height}-${this.fps}fps-${this.duration}s.webm`
      this.loading = false
    }
  }
}
</script>

<style scoped>
#app {
  text-align: left;
  padding: 20px;
}

button {
  margin: 20px;
  padding: 10px 20px;
  font-size: 16px;
}

video {
  margin-top: 20px;
  border: 1px solid #ddd;
}
</style>
